import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/toast_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';


class KqSelectableGridView<T extends IGridViewItemData> extends StatefulWidget {
  /// 是否多选
  final bool multiSelect;

  /// 选中的颜色
  final Color? selectedColor;

  /// 未选中时的颜色
  final Color unselectedColor;

  /// 选中的字体颜色
  final Color selectedTextColor;

  /// 未选中时的字体颜色
  final Color unselectedTextColor;

  /// 不能选时的颜色
  final Color usedTextColor;

  ///显示列数
  final int crossAxisCount;

  ///item的高度是根据item的宽度的比例来计算的，当item宽度小的时候，要调高该值保证item的高度
  final double childAspectRatio;

  ///需要显示的数据
  final List<T>? items;

  /// 不能选时的提示语
  final String? usedNotices;

  /// 是否需要显示不能选时的提示语
  final bool isShowUsedNotices;

  /// 当为单选时点击时的回调，多选时不回调该tap
  final Function(T? data)? onTap;

  /// 当为多选时点击时的回调，单选时不回调该tap
  final Function(List<T>? datas)? onMultiTap;

  const KqSelectableGridView(
      {super.key,
      this.selectedColor,
      this.unselectedColor = const Color(0xFFF5F5F5),
      this.crossAxisCount = 2,
      this.items,
      this.usedNotices,
      this.onTap,
      this.childAspectRatio = 4,
      this.multiSelect = false,
      this.selectedTextColor = const Color(0xFFFFFFFF),
      this.unselectedTextColor = const Color(0xFF595959),
      this.usedTextColor = const Color(0xFFBFBFBF),
      this.onMultiTap,
      this.isShowUsedNotices = true});

  @override
  State<StatefulWidget> createState() => KqSelectableGridViewState<T>();
}

class KqSelectableGridViewState<T extends IGridViewItemData>
    extends State<KqSelectableGridView<T>> {
  @override
  Widget build(BuildContext context) {
    return GridView.count(
      ///Container跟随GridView内容变化高度, shrinkWrap:true;
      shrinkWrap: true,

      ///取消滚动效果physics: NeverScrollableScrollPhysics();
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.zero,
      crossAxisCount: widget.crossAxisCount,
      childAspectRatio: widget.childAspectRatio,
      mainAxisSpacing: 8.r,
      crossAxisSpacing: 8.r,
      children: getItems(),
    );
  }

  List<Widget> getItems() {
    if (widget.items.isNullOrEmpty) {
      return [];
    }
    List<Widget> widgets = [];
    for (T data in widget.items!) {
      widgets.add(
        KqInkWell(
            backgroundColor: data.isSelected
                ? widget.selectedColor ??
                    KqThemeManager.getCommonConfig().mainColor ??
                    const Color(0xFF3A559B)
                : widget.unselectedColor,
            radius: 2.r,
            onTap: () {
              if (data.isUsed) {
                if (widget.isShowUsedNotices) {
                  KqToast.showNormal(
                      widget.usedNotices ?? "");
                }
              } else if (data.isSelected) {
                if (widget.multiSelect) {
                  data.isSelected = false;
                  widget.onMultiTap?.call(getSelectedData());
                  setState(() {});
                } else {
                  data.isSelected = false;
                  widget.onTap?.call(null);
                  setState(() {});
                }
              } else if (!data.isSelected) {
                if (widget.multiSelect) {
                  data.isSelected = true;
                  widget.onMultiTap?.call(getSelectedData());
                  setState(() {});
                } else {
                  clearAllSelectedState();
                  data.isSelected = true;
                  widget.onTap?.call(data);
                  setState(() {});
                }
              }
            },
            child: Container(
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              padding: EdgeInsets.only(left: 12.r, right: 12.r),
              child: Text(
                data.title,
                maxLines: 2,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: data.isSelected
                      ? widget.selectedTextColor
                      : (data.isUsed
                          ? widget.usedTextColor
                          : widget.unselectedTextColor),
                  fontSize: KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .contentFontSize ??
                      12.sp,
                  fontWeight: FontWeight.normal,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            )),
      );
    }
    return widgets;
  }

  clearAllSelectedState() {
    for (T data in widget.items!) {
      data.isSelected = false;
    }
  }

  List<T> getSelectedData() {
    List<T> selectedData = [];
    for (T data in widget.items!) {
      if (data.isSelected) {
        selectedData.add(data);
      }
    }
    return selectedData;
  }
}

class IGridViewItemData {
  ///显示文本
  @JsonKey(includeToJson: false, includeFromJson: false)
  String title;

  /// 是否选中
  @JsonKey(includeToJson: false, includeFromJson: false)
  bool isSelected;

  /// 是否已使用，已使用则不可选择
  @JsonKey(includeToJson: false, includeFromJson: false)
  bool isUsed;

  IGridViewItemData(this.title, {this.isSelected = false, this.isUsed = false});
}
